<template>
    <div>
        <div>测试H5录音功能</div>
        <button @click="startRecording" v-if="!isRecording">开始录音</button>
        <button @click="stopRecording" v-if="isRecording">停止录音</button>
        <audio ref="audioPlayer" controls></audio>
    </div>
</template>

<script>
export default {
    data() {
        return {
            isRecording: false,
            mediaRecorder: null,
            audioChunks: [],
            audioURL: null,
        }
    },
    methods: {
        startRecording() {
            navigator.mediaDevices
                .getUserMedia({ audio: true })
                .then((stream) => {
                    this.mediaRecorder = new MediaRecorder(stream)
                    this.mediaRecorder.ondataavailable = (e) => {
                        this.audioChunks.push(e.data)
                    }
                    this.mediaRecorder.onstop = () => {
                        const audioBlob = new Blob(this.audioChunks, { type: 'audio/ogg; codecs=opus' })
                        this.audioURL = URL.createObjectURL(audioBlob)
                        this.$refs.audioPlayer.src = this.audioURL
                    }
                    this.mediaRecorder.start()
                    this.isRecording = true
                })
                .catch((error) => {
                    console.error('无法访问麦克风：', error)
                })
        },
        stopRecording() {
            this.mediaRecorder.stop()
            this.isRecording = false
        },
    },
}
</script>
